package com.definesys.smecrailtransit;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Handler;
import android.support.v4.app.Fragment;

import android.os.Bundle;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.definesys.smecrailtransit.SmecManager.SmecDialog.SmecDialog;
import com.definesys.smecrailtransit.SmecManager.SmecSession.SmecSession;
import com.definesys.smecrailtransit.api.SmecRailConstant;
import com.definesys.smecrailtransit.base.SmecBaseActivity;


import com.definesys.smecrailtransit.databinding.ActivityMainBinding;
import com.definesys.smecrailtransit.module.EleRecord.EleRecordFragment;
import com.definesys.smecrailtransit.module.LineReport.LineReportFragment;
import com.definesys.smecrailtransit.module.Login.LoginActivity;
import com.definesys.smecrailtransit.module.MonthForm.MonthFormFragment;
import com.definesys.smecrailtransit.module.RealStatus.RealStatusFragment;
import com.definesys.smecrailtransit.module.RealTime.RealTimeFragment;
import com.definesys.smecrailtransit.module.SiteDetails.SiteDetailsFragment;
import com.definesys.smecrailtransit.module.TotalTime.TotalTimeFragment;
import com.definesys.smecrailtransit.module.lineCharts.LineChartsActivity;
import com.definesys.smecrailtransit.receiver.JPushReceiver;
import com.definesys.smecrailtransit.receiver.receiverBean.JPushExtras;
import com.definesys.smecrailtransit.widget.TopBarLayout;

import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.github.mzule.activityrouter.annotation.Router;
import com.github.mzule.activityrouter.router.Routers;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;


import java.util.ArrayList;
import java.util.HashMap;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

import static com.definesys.smecrailtransit.module.LineReport.LineReportFragment.JPUSH_LOAD_LINE_REPORT;
import static com.definesys.smecrailtransit.module.MonthForm.MonthFormFragment.JPUSH_LOAD_MONTH_FORM;
import static com.definesys.smecrailtransit.module.Navigation.NavigationActivity.MAINACTIVITY_FINISH;
import static com.definesys.smecrailtransit.module.Navigation.NavigationAdapter.NavigationAdapter.NAVIGATION;
import static com.definesys.smecrailtransit.module.TotalTime.TotalTimeFragment.JPUSH_LOAD_RUN_TIME;
import static com.definesys.smecrailtransit.receiver.JPushReceiver.ACTIVITY_OPENDED;

@Router("MainActivity")
public class MainActivity extends SmecBaseActivity {

    public static final String JPUSH_REFRESH="JPUSH_REFRESH";
    public static final String WAY_TO_FRAGMNET="WAY_TO_FRAGMNET";
    private ActivityMainBinding activityMainBinding;
    private ArrayList<Fragment> fragmentArrayList;
    public int fragmentChange=0;
    private TopBarLayout topBarLayout;
    private NormalDialog normalDialog;
    private DrawerLayout drawerLayout;

    private Handler mHandler=new Handler(){};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityMainBinding=DataBindingUtil.setContentView(this,R.layout.activity_main);
        activityMainBinding.setCurrentItem(fragmentChange);
        _initView();
        _getDataFromIntent();
    }

    @Override
    public Object getPresenter() {
        return null;
    }

    /**
     * 从Intent中获取数据
     */
    private void _getDataFromIntent(){
        //当从导航页进来时
        String[] param = getIntent().getStringArrayExtra(NAVIGATION);
        if( param != null && param.length != 0 ){
            String position = param[0];
            if(position !=null && !position.equals("")){
                int navPosition=Integer.parseInt(position);
                _changeFragment(navPosition);

                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put("from",param[1]);
                hashMap.put("to",param[2]);

                activityMainBinding.getRoot().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(navPosition == 3){
                            mRxBus.post(JPUSH_LOAD_MONTH_FORM,hashMap);
                        }
                        if(navPosition == 4){
                            mRxBus.post(JPUSH_LOAD_RUN_TIME,hashMap);
                        }
                    }
                },210);
                return;
            }
        }

        //当为后台应用时
        String[] param1 = getIntent().getStringArrayExtra("JPUSH_TYPE");
        if(param1 != null && param1.length != 0){
            String type= param1[0];
            if(type != null && !type.equals("") ){
                if(type.equals(JPushReceiver.JPUSH_TYPE_REAL)){
                    fragmentChange = 0;
                }
                if(type.equals(JPushReceiver.JPUSH_TYPE_REPORT)){
                    fragmentChange = 1;
                }
                if(type.equals(JPushReceiver.JPUSH_TYPE_STATISTICS)){
                    fragmentChange = 3;
                }
                if(type.equals(JPushReceiver.JPUSH_TYPE_RUNTIME)){
                    fragmentChange = 4;
                }
                if(type.equals(JPushReceiver.JPUSH_TYPT_LINE_REPORT)){
                    fragmentChange = 5;
                }

                _changeFragment(fragmentChange);

                HashMap<String,String> hashMap = new HashMap<>();
                hashMap.put("from",param1[1]);
                hashMap.put("to",param1[2]);

                activityMainBinding.getRoot().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(fragmentChange == 3){
                            mRxBus.post(JPUSH_LOAD_MONTH_FORM,hashMap);
                        }
                        if(fragmentChange == 4){
                            mRxBus.post(JPUSH_LOAD_RUN_TIME,hashMap);
                        }
                    }
                },210);
            }
        }

    }

    /**
     * 侧滑切换Fragment
     * @param view
     */
    public void switchFragment(View view){
        switch (view.getId()){
            case R.id.real_msg:
                fragmentChange = 0;
                break;
            case R.id.site_details:
                fragmentChange = 1;
                break;
            case R.id.real_status:
                fragmentChange = 2;
                break;
            case R.id.fault_st:
                fragmentChange = 3;
                break;
            case R.id.operator_status:
                fragmentChange = 4;
                break;
            case R.id.line_report:
                fragmentChange = 5;
                break;
            case R.id.smec_record_navi:
                fragmentChange = 6;
                break;
            case R.id.login_out:
                _getDialog();
                normalDialog.show();
                return;
        }
        drawerLayout.closeDrawer(GravityCompat.END);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                _changeFragment(fragmentChange);
            }
        },200);
    }

    /**
     * 切换Fragment
     * @param navPosition
     */
    private void _changeFragment(int navPosition){

        fragmentChange = navPosition;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    if(SmecRailConstant.getNavigationTitle()== null){
                        Intent intent=new Intent(activityMainBinding.getRoot().getContext(),LoginActivity.class);
                        activityMainBinding.getRoot().getContext().startActivity(intent);
                        return;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                topBarLayout.getTvTextTitle().setText(getString((SmecRailConstant.getNavigationTitle().get(fragmentChange))));
                mRxBus.post(WAY_TO_FRAGMNET,fragmentChange+"");
            }
        },200);
        activityMainBinding.pager.setCurrentItem(fragmentChange,false);
        activityMainBinding.invalidateAll();
    }

    /**
     * 初始化数据
     */
    private void _initView(){
        fragmentArrayList=new ArrayList<>();
        fragmentArrayList.add(RealTimeFragment.newInstance());//实时故障 0
        fragmentArrayList.add(SiteDetailsFragment.newInstance());//站点详情 1
        fragmentArrayList.add(RealStatusFragment.newInstance());//实时状态 2
        fragmentArrayList.add(MonthFormFragment.newInstance());//故障统计 3
        fragmentArrayList.add(TotalTimeFragment.newInstance());//运行时长 4
        fragmentArrayList.add(LineChartsActivity.newInstance());
        fragmentArrayList.add(EleRecordFragment.newInstance());
        activityMainBinding.navi.setUsername(SmecSession.getSmecUser().getUserName());
        activityMainBinding.pager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {

            public int getCount() {
                return fragmentArrayList.size();
            }

            public Fragment getItem(int position) {
                return fragmentArrayList.get(position);
            }
        });
        activityMainBinding.pager.setOffscreenPageLimit(1);

        Observable.create(new Observable.OnSubscribe<Object>() {
            @Override
            public void call(Subscriber<? super Object> subscriber) {
                _setTopNaviMsg();
            }
        }).subscribeOn(Schedulers.io()).
                unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Object>() {
                    @Override
                    public void call(Object o) {
                        Log.e("当前时间：",System.currentTimeMillis()+"");
                    }
                });
    }

    /**
     * 设置导航栏侧滑信息
     */
    private void _setTopNaviMsg(){
        topBarLayout = activityMainBinding.topBarLayout;
        drawerLayout = activityMainBinding.drawerLayout;
        activityMainBinding.topBarLayout.setTopBarListener(new TopBarLayout.TopBarListener() {
            @Override
            public void setOnLeftClickListener() {
                finish();
                appManager.finishActivity();
                mRxBus.post(MAINACTIVITY_FINISH,new Object());
            }

            @Override
            public void setOnRight1ClickListener() {

            }
            @Override
            public void setOnRight2ClickListener() {
                showOrHideRecycler();
            }
        });
        drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                activityMainBinding.getRoot().setClickable(false);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                activityMainBinding.getRoot().setClickable(true);
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
        TextView nvaiView=topBarLayout.gettvTextRightSecond();
        ViewGroup.LayoutParams layoutParams=nvaiView.getLayoutParams();
        layoutParams.height = 60;
        layoutParams.width = 60;
        nvaiView.setBackground(getResources().getDrawable(R.drawable.ele_navi));
    }

    /**
     * 实例化dialog
     * @return
     */
    private NormalDialog _getDialog(){
        if(normalDialog == null){
            normalDialog= SmecDialog.getInstance(this,"退出登录吗?");

            normalDialog.setOnBtnClickL(
                    new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            normalDialog.dismiss();
                        }
                    },
                    new OnBtnClickL() {
                        @Override
                        public void onBtnClick() {
                            normalDialog.dismiss();
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    finish();
                                    mRxBus.post(LoginActivity.LOGIN_SEWITCH,new Object());
                                }
                            },300);
                        }
                    });
        }
        return normalDialog;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {
                    @Tag(ACTIVITY_OPENDED)
            }
    )
    public void openedActivity(JPushExtras jPushExtras){
        String funName = jPushExtras.getFunName();
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("from",jPushExtras.getFrom());
        hashMap.put("to",jPushExtras.getTo());

        if(funName !=null && !funName.equals("")){
            if(funName.equals(JPushReceiver.JPUSH_TYPE_REAL)){
                if(fragmentChange == 0){
                    mRxBus.post(JPUSH_REFRESH,new Object());
                    return;
                }
                fragmentChange = 0;
                _changeFragment(fragmentChange);

            } else if(funName.equals(JPushReceiver.JPUSH_TYPE_REPORT)){
                if(fragmentChange == 1){
                    return;
                }
                fragmentChange = 1;
                _changeFragment(fragmentChange);

            }else if(funName.equals(JPushReceiver.JPUSH_TYPE_STATISTICS)){
                //故障月度统计
                if(fragmentChange == 3){
                    mRxBus.post(JPUSH_LOAD_MONTH_FORM,hashMap);
                    return;
                }
                fragmentChange = 3;
                _changeFragment(fragmentChange);
                mRxBus.post(JPUSH_LOAD_MONTH_FORM,hashMap);

            }else if(funName.equals(JPushReceiver.JPUSH_TYPE_RUNTIME)){
                //运行时长月度汇报
                if(fragmentChange == 4){
                    mRxBus.post(JPUSH_LOAD_RUN_TIME,hashMap);
                    return;
                }
                fragmentChange = 4;
                _changeFragment(fragmentChange);
                mRxBus.post(JPUSH_LOAD_RUN_TIME,hashMap);

            }else if(funName.equals(JPushReceiver.JPUSH_TYPT_LINE_REPORT)){
                //线路简报
                //运行时长月度汇报
                if(fragmentChange == 5){
                    mRxBus.post(JPUSH_LOAD_LINE_REPORT,new Object());
                    return;
                }
                fragmentChange = 5;
                _changeFragment(fragmentChange);
            }
        }
    }


    public void showOrHideRecycler() {
        if (drawerLayout.isDrawerOpen(GravityCompat.END)) {
            drawerLayout.closeDrawer(GravityCompat.END);
        } else {
            drawerLayout.openDrawer(GravityCompat.END);
        }
    }

}
